package com.java2104.controller;

import com.java2104.entity.Dept;
import com.java2104.entity.Employee;
import com.java2104.entity.Job;
import com.java2104.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @RequestMapping("/list")
    @ResponseBody
    public List<Employee> list(Employee employee){
        return employeeService.getEmployees(employee);
    }

    @PostMapping(path = "/delete",consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String delete(@RequestBody List<Integer> ids, HttpServletResponse response){
        int n = employeeService.delete(ids);
        response.setContentType("text/html;charset=utf-8");
        return "成功删除了" + n + "个文档";
    }

    @InitBinder//会在处理方法执行前，将参数类型进行判断和转化
    public void initBinder(WebDataBinder webDataBinder, String height) {
        //负责将客户端发送的请求参数中的 "yyyy-MM-dd" 的日期转换成 java.util.Date的对象
        CustomDateEditor customDateEditor
                = new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false);
        webDataBinder.registerCustomEditor(java.util.Date.class, customDateEditor);
        webDataBinder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
        if (height==null || height.equals("")) {
            webDataBinder.setDisallowedFields("height");
        }
    }

    @RequestMapping("/update")
    @ResponseBody
    public String update(Employee employee){
        employeeService.update(employee);
        return "success";
    }
    @RequestMapping("/edit/{eId}")
    public String edit(@PathVariable Integer eId, Model model) throws IOException {
        model.addAttribute("employee",employeeService.get(eId));
        return "employee/showUpdateEmployee";
    }
    @PostMapping("/add")
    @ResponseBody
    public Map insert(Employee employee){
     return    employeeService.insert(employee);
    }
}
